class base {
    _tableName;
    _db;
    _debug = true;
    _auto = {};
    _createTime;
    _updateTime;
    pageSize = 15;

    constructor() {
        this._dbConfig = require('../config');
        this._db = require('../db');
        this._tableName = this._dbConfig.prefix + this.constructor.name;
    }

    getLimit(page = 1) {
        page || (page = 1);
        return (page - 1) * this.pageSize + ',' + this.pageSize;
    }

    /**
     * 查询列表
     * @param where
     * @param limit
     * @param field
     * @returns {Promise<unknown>}
     */
    list(where = {}, limit = null, field = '*') {
        let whereStr = this.whereFormat(where), sql;
        sql = 'select ' + field + ' from ' + this._tableName + ' where ' + whereStr
        return new Promise((resolve, reject) => {
            this._debug && console.log('【查询sql】-> ', sql);
            this._db.query(sql, (error, row) => {
                if (error)
                    reject(error)
                else
                    resolve(row);
            });
        });
    }

    /**
     * 插入数据
     * @param data
     * @returns {Promise<unknown>}
     */
    add(data = {}) {
        this._createTime && (data[this._createTime] = parseInt((new Date()).getTime() / 1000));
        this._updateTime && (data[this._updateTime] = parseInt((new Date()).getTime() / 1000));
        let sql = 'insert into ' + this._tableName + '(' + Object.keys(data).join(',') + ') values(\'' + Object.values(data).join("','") + '\')';
        return new Promise((resolve, reject) => {
            this._debug && console.log('【插入sql】-> ', sql);
            this._db.query(sql, (error, row) => {
                if (error) reject(error)
                else {
                    if ('affectedRows' in row && row.affectedRows) {
                        resolve(row);
                    } else {
                        reject('创建失败');
                    }
                }
            });
        });
    }

    /**
     * 更新数据
     * @param data
     * @param where
     * @returns {Promise<unknown>}
     */
    update(data, where) {
        this._updateTime && (data[this._updateTime] = parseInt((new Date()).getTime() / 1000));
        let fieldArr = [];
        for (let k in data) {
            fieldArr.push(`${k}='${data[k]}'`);
        }
        let whereStr = this.whereFormat(where),
            sql = 'update ' + this._tableName + ' set ' + fieldArr.join(',') + ' where ' + whereStr;
        return new Promise((resolve, reject) => {
            this._debug && console.log('【更新sql】-> ', sql);
            this._db.query(sql, (error, row) => {
                if (error)
                    reject(error)
                else {
                    if ('affectedRows' in row && row.affectedRows) {
                        resolve(row);
                    } else {
                        reject('更新失败');
                    }
                }
            });
        });
    }

    /**
     * 格式化条件
     * @param where
     */
    whereFormat(where = {}) {
        let whereStr = '1 ', op = '=', escape = false, val;
        for (let i in where) {
            if (Object.prototype.toString.call(where[i]) === '[object Object]') {
                op in where[i] && (op = where[i].op);
                escape in where[i] && (escape = where[i].escape);
                val = where[i].val;
            } else if (Object.prototype.toString.call(where[i]) === '[object Array]') {
                escape = true;//含特殊字符
                op = 'in';
                val = '(' + (where[i].length ? where[i].join(',') : 0) + ')';
            } else val = where[i];
            whereStr += ` and ${i} ${op} ` + (escape ? `${val}` : `'${val}'`);
        }

        return whereStr;
    }
}

module.exports = base;